# -*- coding: utf-8 -*-
#build app images.py

# build docker

import os
import json
import time
import sys
import logging


import logging
# 创建一个logger
logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('/root/.jenkins/sry_jenkins_plugin.log')
logger.addHandler(fh)
logger.info("sry jenkins plugin")

'''
调用说明：

build_app_images.py 应用名称 月度版本  基础镜像地址 配置文件
例： build_app_images.py app80 192.168.1.150/base/app1:20161113120000  test_jenkinsConfiguration_2016xxx.tar
'''


print '===== thomas test print ====== '

def generate_docker_file(base_iamge, app_type, work_dir, config_name, config_dest_path,  registry_addr, app_build_time):

    logging.info("base_image: %s, \n"
                 "app_type: %s, \n"
                 "config_name: %s, \n"
                 % (base_image, app_type, config_name))

    os.chdir(work_dir)
    with open("Dockerfile", "w") as f:
        f.write("FROM %s\n\n" % base_iamge)
        f.write("ADD %s %s " % (config_name, config_dest_path))

    app_image_name = base_iamge.replace("base", app_type)

    #delete if there has output file
    if os.path.exists("output"):
        os.remove(os.path.join(work_dir, "output"))
    else:
        pass

    # TODO modify
    cmd_str = '''
        docker build -t %s_%s . >> output\n
        docker login -u admin -p Harbor12345 %s >> output\n
        docker push %s_%s  >> output\n
    ''' % (app_image_name, app_build_time, registry_addr, app_image_name, app_build_time)

    logger.info("cmd: %s " % cmd_str)
    os.system(cmd_str)

    os.remove(os.path.join(work_dir, "Dockerfile"))
    os.remove(os.path.join(work_dir, "output"))
    logger.info("clean Dockerfile, output ")


def add_records_images_files(app_name, app_type, app_image):
    #work_space = os.environ['WORKSPACE']
    #print "work_space = %s" % work_space

    print "host = %s" % os.environ['HOME']

    sry_image_file_path = '%s/.jenkins/sry_images_list.json' % (os.environ['HOME'])
    # 检查文件是否存在,不存在就创建
    json_obj = {}
    if not os.path.exists(sry_image_file_path):
        tmp_dict = {}
        tmp_dict['records'] = []
        tmp_str = json.dumps(tmp_dict)

        tmp_fp = open(sry_image_file_path, 'wb')
        tmp_fp.write(tmp_str)
        tmp_fp.close()

    fp = file(sry_image_file_path)
    json_obj = json.load(fp)

    new_dict = {}
    new_dict['appname'] = app_name
    new_dict['type'] = app_type
    new_dict['images'] = app_image
    #new_dict['time'] = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
    new_dict['tag'] = app_img_tag

    json_obj['records'].append(new_dict)

    json_str = json.dumps(json_obj)

    fp = open(sry_image_file_path, 'wb')
    fp.write(json_str)
    fp.close()


if __name__ == "__main__":

    app_name = sys.argv[1]
    #app_type = sys.argv[2]
    month_version = sys.argv[2]
    base_image = sys.argv[3]
    cfg_name = sys.argv[4]
    cfg_dest_path = sys.argv[5]
    app_type = cfg_name.split('_')[0]
    app_image = base_image.replace('base', app_type)
    logging.info("app_image: %s" % app_image)

    current_timestamp = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
    app_image_new = app_image + '_' + current_timestamp
    logging.info("new app_image: %s" % app_image_new)

    cfg_mgr_local_dir = os.path.join(os.environ['HOME'], 'sry_image_cfg_mgr', app_name, month_version)


    generate_docker_file(base_iamge=base_image, app_type=app_type, work_dir=cfg_mgr_local_dir,
                         config_name=cfg_name, config_dest_path=cfg_dest_path, registry_addr= '192.168.99.105',
                         app_build_time= current_timestamp)

    add_records_images_files(app_name, app_type, app_image_new)
